package cn.com.dhcc.turbo.service.registry.sync.http;

import java.util.HashMap;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.handler.remotehandler.socket.ICallBack;
import cn.com.dhcc.app.core.handler.remotehandler.socket.ISendDataClient;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.tag.CommonStaticCode.SUCCESSFAIL;
import cn.com.dhcc.app.core.util.HttpClientUtil;
import cn.com.dhcc.app.core.util.JsonUtil;
import cn.com.dhcc.app.core.util.Status;
import cn.com.dhcc.app.core.util.StrUtil;
import cn.com.dhcc.app.core.util.XstreamUtil;
import cn.com.dhcc.app.pub.core.consts.AppIocBean;
import cn.com.dhcc.turbo.entity.api.Data;
import cn.com.dhcc.turbo.entity.api.Exch;
import cn.com.dhcc.turbo.service.exch.DistributedNodeInfoService;
import cn.com.dhcc.turbo.service.registry.sync.ISynchronizeHandler;
import cn.com.dhcc.turbo.service.registry.sync.SyncCallBack;
/**
 * http 数据同步
 * @author qiao
 * @2015-10-21 @上午10:55:34
 */
@Service(AppIocBean.HTTP_SEND_DATA_CLIENT)
public class HttpSendDataClient implements ISendDataClient{

	Logger logger = Log.getLogger(LOGTYPE.TURBO);
	ISynchronizeHandler iSynchronizeHandler = null;
	@Override
	public void sendData(String installUrl, int port, Object dataToSend,
		ICallBack iCallBack) throws Exception {
		//获取同步地址
		String registSyncUrl = DistributedNodeInfoService.getRegistSyncUrl(installUrl);
		//封装数据
		Exch exch=new Exch();
		exch.setActionName("receiveData");
		Data data = new Data();
		data.setData(JsonUtil.toJson(dataToSend));
		exch.setContent(data);
		HashMap<String, String> paramMap=new HashMap<String, String>();
		try {
			paramMap.put("exch", XstreamUtil.toXml(exch));
		} catch (Exception e) {
			throw new ServiceException("同步数据失败:"+e.getMessage());
		}
		//调动同步接口
		Status status=HttpClientUtil.post(registSyncUrl, paramMap);
		//封装返回
		String resData = (String) status.getData();
		SyncCallBack syncCallBack  = null;
		if(StrUtil.isNotBank(resData)){
			syncCallBack = JsonUtil.toObject(resData, SyncCallBack.class);
			
		}
		if(syncCallBack==null){//调用失败了
			syncCallBack = new SyncCallBack();
			syncCallBack.setResult(status.isSuccess()?SUCCESSFAIL.SUCCESS:SUCCESSFAIL.FAIL);
			syncCallBack.setMsg(status.getMsg());
		}
		iCallBack.recevieCallBackData(syncCallBack);
	}
}
